package com.ruoyi.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import com.ruoyi.system.domain.ParamUpload;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class UnzipAndListFilesUtils {
    public static List unzipAndPrintPaths(String zipFilePath, String destDir,String strdir) {
        //所有的文件路径
        List<String> filePaths = new ArrayList<>();
        List<ParamUpload> paramUploadList = new ArrayList<ParamUpload>();

        // 去除文件名中的后缀名
        // 获取文件的完整路径
        File file = new File(zipFilePath);
        String filePath1 = file.getName();
        int pos = filePath1.lastIndexOf(".");
        String dirname = filePath1.substring(0, pos);
        Integer i = 0;
        File destDirectory = new File(destDir);
        if (!destDirectory.exists()) {
            destDirectory.mkdirs();
        }
        try (ZipFile zipFile = new ZipFile(zipFilePath, Charset.forName("gbk"))) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            while (entries.hasMoreElements()) {

                ZipEntry entry = entries.nextElement();
                if (entry.getName().indexOf(".") == -1)
                    continue;


                String temdir = destDir + File.separator + dirname + "_" + i;
                //String filePath = destDir + File.separator + entry.getName();
                //产生新的文件名字
                String extension = entry.getName().substring(entry.getName().lastIndexOf(".") + 1);
                String filename = entry.getName().substring(0, entry.getName().lastIndexOf("."));
                String filePath = temdir + "." + extension;
                String strFilePath = strdir + dirname + "_" + i + "." + extension;
                long size = entry.getSize();
                List<String> stringList = Arrays.asList("doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "epub", "vsd", "pot", "pps", "rtf", "wps", "et", "dps", "pdf", "txt");
                if (!StringUtils.matches(extension, stringList)&&!entry.isDirectory()) {
                    ParamUpload paramUpload = new ParamUpload();
                    paramUpload.setTitle(filename);
                    paramUpload.setPath("");
                    paramUpload.setExten(extension);
                    paramUploadList.add(paramUpload);
                    continue;

                }
                destDirectory = new File(temdir);
                if (!destDirectory.exists()) {
                    destDirectory.mkdirs();
                }


                // 确保目标文件路径的父目录存在
                File entryDestination = new File(filePath);
                File parentDirectory = entryDestination.getParentFile();
                if (parentDirectory != null && !parentDirectory.exists()) {
                    parentDirectory.mkdirs();
                }
                if (!entry.isDirectory()) {
                    // 提取文件
                    try (InputStream is = zipFile.getInputStream(entry);
                         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
                        byte[] bytesIn = new byte[4096];
                        int read;
                        while ((read = is.read(bytesIn)) != -1) {
                            bos.write(bytesIn, 0, read);
                        }
                    }
                    // 打印文件路径
                    System.out.println("Extracted: " + filePath);
                    filePaths.add(filePath);
                } else {
                    // 如果是目录，则创建目录（注意：在上面的mkdirs调用中已经处理了）
                    // 这里也可以选择打印目录路径
                    System.out.println("Created directory: " + filePath);
                }
                if (StringUtils.matches(extension, stringList)) {
                    ParamUpload paramUpload = new ParamUpload();
                    paramUpload.setTitle(filename);
                    paramUpload.setKeyword(filename);
                    paramUpload.setExten(extension);
                    paramUpload.setPath(strFilePath);
                    paramUpload.setSize(size);
                    paramUploadList.add(paramUpload);
                }
                else
                    continue;
                i++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取特定类型的文件信息
        /*for (String filePath : filePaths) {
            if (filePath.endsWith(".shp")) {
                return filePath;
            }
        }*/
        File zipfile = new File(zipFilePath);
        if(zipfile.exists())
            zipfile.delete();
        return  paramUploadList;
    }

    //获取父目录
    public static String  getParentFilepath(String fullPath ) {
        Path path = Paths.get(fullPath);
        // 使用getParent()方法来获取父路径，即目录部分
        Path directoryPath = path.getParent();
        if (directoryPath != null) {
            System.out.println("Directory path: " + directoryPath);
            return directoryPath.toString();
        } else {
            System.out.println("No parent directory.");
            return null;
        }
    }
    public static void zipFiles(String zipFilePath, List<ParamUpload> files) {
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
            byte[] buffer = new byte[1024];
            for (int i=0;i<files.size();i++) {
                File sourceFile = new File(files.get(i).getPath());
                //阿里云oss 上传

                //***************/

                try (FileInputStream fis = new FileInputStream(sourceFile)) {
                    zos.putNextEntry(new ZipEntry(files.get(i).getTitle()));
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void zipFiles(String zipFilePath, List<ParamUpload> files,String endpoint,String keyid,String keysecret,String bucket) {
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
            byte[] buffer = new byte[1024];
            for (int i = 0; i < files.size(); i++) {
                File sourceFile = new File(files.get(i).getPath());
                 if(sourceFile.exists()) {
                     try (FileInputStream fis = new FileInputStream(sourceFile)) {
                         zos.putNextEntry(new ZipEntry(files.get(i).getTitle()));
                         int length;
                         while ((length = fis.read(buffer)) > 0) {
                             zos.write(buffer, 0, length);
                         }
                     }
                 }
                 else
                 {
                     OSS ossClient = new OSSClientBuilder().build(endpoint,keyid,keysecret);
                     OSSObject ossObject = ossClient.getObject(bucket,files.get(i).getPath());
                     InputStream inputStream = ossObject.getObjectContent();
                     try (InputStream fis =  inputStream ) {
                         zos.putNextEntry(new ZipEntry(files.get(i).getTitle()));
                         int length;
                         while ((length = fis.read(buffer)) > 0) {
                             zos.write(buffer, 0, length);
                         }
                     }

                 }
            }
        }catch(IOException e){
                    e.printStackTrace();
                }

    }
    public static String fenci(@PathVariable("keyword") String keyword)
    {
        List<String> list = new ArrayList<>();
        Segment segment = HanLP.newSegment();
        List<Term> termList = segment.seg(keyword);
        for (Term term : termList) {
            //System.out.println(term.word);
            list.add(term.word);
        }
        return list.stream().map(String::valueOf).collect(Collectors.joining(","));
    }


}

